// pages/ai/baseAI/baseAI.js
import { createConversationAPI, sendMessageAPI, retrieveConversationAPI } from '../../../API/ai/index.js';

Page({
  data: {
    conversationId: '',
    userId: '', // 动态获取用户ID
    userQuestion: '',
    messageList: [], // 对话历史
    hotQuestions: [
      '选修课怎么选比较合理？选了之后能退课或换课吗？有什么时间限制？',
      '期末挂科了怎么办？补考/重修的时间和流程是什么？会影响绩点吗？',
      '想申请缓考（比如因病），需要提交什么材料？向谁审批？'
    ],
    isLoading: false, // 加载状态
    greeting: '你好，我是你的AI专属辅导员，你有什么不懂的问题，都可以问我。'
  },

  async onLoad() {
    // 获取用户ID（实际应从登录态获取）
    this.setData({ userId: wx.getStorageSync('userId') || 'student_user_001' });
    await this.createConversation();
    // 添加欢迎语到对话历史
    this.addMessage('ai', this.data.greeting);
  },

  /**
   * 创建会话
   */
  async createConversation() {
    try {
      this.setData({ isLoading: true });
      const { userId } = this.data;
      const res = await createConversationAPI({ user_id: userId });
      
      if (res.code === 0) {
				console.log("会话ID:",res.data.id)
        this.setData({ conversationId: res.data.id });
      } else {
        wx.showToast({ title: '创建对话失败', icon: 'none' });
        setTimeout(() => this.createConversation(), 2000); // 重试
      }
    } catch (error) {
      console.error('创建对话失败:', error);
    } finally {
      this.setData({ isLoading: false });
    }
  },

  /**
   * 发送消息
   */
  async sendMessage() {
    const { userQuestion, conversationId, userId } = this.data;
    if (!userQuestion.trim() || !conversationId) return;

    // 添加用户消息到历史
    this.addMessage('user', userQuestion);
    this.setData({ userQuestion: '', isLoading: true });

    try {
      const res = await sendMessageAPI({
        conversation_id: conversationId,
        user_id: userId,
        content: userQuestion,
        content_type: 'text'
      });
			console.log(res)
			this.getMessageHistory({ conversation_id: this.data.conversationId, limit: 20 })
      if (res.code === 0) {
        // 假设API返回的data包含AI回复
        this.addMessage('ai', res.data.content);
      } else {
        this.addMessage('ai', `抱歉，未能获取回复: ${res.msg}`);
      }
    } catch (error) {
      this.addMessage('ai', '消息发送失败，请重试');
    } finally {
      this.setData({ isLoading: false });
    }
  },

  /**
   * 添加消息到历史记录
   */
  addMessage(role, content) {
    const message = {
      role,
      content,
      time: new Date().toLocaleTimeString()
    };
    this.setData({
      messageList: [...this.data.messageList, message]
    });
    // 滚动到底部
    this.scrollToBottom();
  },

  /**
   * 滚动到消息底部
   */
  scrollToBottom() {
    wx.createSelectorQuery().select('#chat-container').boundingClientRect(rect => {
      wx.pageScrollTo({ scrollTop: 300, duration: 300 });
    }).exec();
  },

  /**
   * 处理输入变化
   */
  onInputChange(e) {
    this.setData({ userQuestion: e.detail.value });
  },

  /**
   * 快捷提问
   */
  quickQuestion(e) {
    const question = e.currentTarget.dataset.question;
    this.setData({ userQuestion: question });
    this.sendMessage();
  },

  /**
   * 查看会话信息
   */
  async retrieveConversation() {
    const { conversationId, userId } = this.data;
    if (!conversationId || !userId) {
      console.log('查看会话失败：缺少conversationId或userId');
      return;
    }

    try {
      const response = await retrieveConversationAPI({
        conversation_id: conversationId,
        user_id: userId
      });

      console.log('会话检索响应:', response);

      if (response.code === 0) {
      } else {
        console.log('❌ 获取会话信息失败:', response.msg || response.message);
      }
    } catch (error) {
      console.log('💥 查看会话出错:', error);
    } finally {
      console.log('🏁 查看会话流程结束');
    }
  },

	  /**
   * 获取消息历史
   */
  async getMessageHistory() {
    const { conversationId, userId } = this.data;
    if (!conversationId || !userId) {
      console.log('❌ 获取消息历史失败：缺少conversationId或userId');
      return;
    }

    try {
      console.log('📚 开始获取消息历史...');
      console.log('会话ID:', conversationId);
      console.log('用户ID:', userId);

      const response = await getMessageHistoryAPI({
        conversation_id: conversationId,
        user_id: userId
      });

      console.log('📋 消息历史响应:', response);

      if (response.code === 0) {
        console.log('✅ 消息历史获取成功！');
        if (response.data && response.data.length > 0) {
          console.log('💬 最新消息:', response.data[response.data.length - 1]);
        }
      } else {
        console.log('❌ 获取消息历史失败:', response.msg || response.message);
      }
    } catch (error) {
      console.log('💥 获取消息历史出错:', error);
    } finally {
      console.log('🏁 获取消息历史流程结束');
    }
  },

  // 页面其他生命周期方法保持不变...
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() { wx.stopPullDownRefresh(); },
  onReachBottom() {},
  onShareAppMessage() {}
});